use strict;
use warnings;
use CGI q(:standard);
use POSIX qw(ceil);
#use DateTime::Format::MySQL;

require 'http.pl';

@forum::cookies = ();
$forum::http_header = {-cookie=>\@forum::cookies, -content_type=>'text/html'};
$forum::root_path = '/~sfoley/forum/';

$forum::preview_text = 'Preview';
$forum::email = 'sfoley@alum.wpi.edu';

sub forum_error
{
	my $err = shift;
	$err = $forum::errmsg unless (defined $err);
	return div({-class=>'error'}, escapeHTML($err), @_);
}
sub forum_start
{
	my @retval =
	(
		start_html(-style=>{-src=>$forum::root_path.'forum.css'},
				   -title=>'Perl Message Board',
				   -head=>Link({-rel=>'icon',
								-type=>'image/gif',
								-href=>$forum::root_path.'favicon.gif'})),
		div({-id=>'header'},
			div({-id=>'banner'},
				div({-style=>'padding:1px'}, # stupid firefox
					h1(a({-href=>$forum::root_path}, 'Orange Root'))),
				div({-id=>'box'},
					a({-href=>'members.cgi'},
						span({-class=>'boxc'},'Members'))
#					a({-href=>'mbcode.cgi'},
#						span({-class=>'boxc'},'MBCode')),
#					a({-href=>'about.cgi'},
#						span({-class=>'boxc'},'About')))),
						)),
			@_),
		'<div id="content">'
	);
	return wantarray ? @retval : "@retval";
}
sub forum_end
{
	my $es = $forum::num_queries == 1 ? 'y' : 'ies';
	my @retval =
	(
		'</div>',
		div({-id=>'footer'},
			($forum::num_queries ?
				"$forum::num_queries quer$es: $forum::total_time seconds".br():
				''),
			'Operating System: Linux (Red Hat distribution)', br(),
			'Language: perl', br(),
			'Editor: vim', br(),
			'Database: MySQL', br(),
			'Please direct any questions or concerns to ',
			a({-href=>"mailto:$forum::email"}, $forum::email)),
		end_html(),
		"\n"
	);
	return wantarray ? @retval : "@retval";
}
sub get_sess_id
{
	my $sess_id = cookie('forum_sess_id');
	# $sess_id = url_param('forum_sess_id') if (!defined $sess_id); # not yet
	return defined $sess_id ? $sess_id : 0;
}
sub forum_cpanel
{
	my $retval = '';
	
	my $user = shift;
	if ($user)
	{
		my $admin = '';
		if ($user->{PRIV} eq 'A')
		{
			$admin = '('.a({-href=>'admin.cgi'}, 'MySQL').')';
		}
		$retval =
			div({-class=>'ftable wide'},
				div({-class=>'ftd'},
					'Welcome,',
					span({-class=>'usernm'},
						a({-href=>"member.cgi?id=$user->{ID}"},
							escapeHTML($user->{USERNM}))),
					$admin),
				div({-class=>'ftd ralign'},
					a({-href=>'logout.cgi', -class=>'strong'}, 'Logout')));
	}
	else
	{
		#my $http_referer = param('http_referer');
		#$http_referer = self_url() if (!defined $http_referer);
		$retval =
			div({-class=>'ftable wide'},
				div({-class=>'ftd'},
					start_form(-action=>'login.cgi', -method=>'post'),
					hidden(-name=>'http_referer', -value=>self_url()),
					'Username: ',
					textfield(-name=>'username', -size=>16, -maxlength=>24),
					' Password: ',
					password_field(-name=>'password',-size=>16,-maxlength=>24),
					submit(-name=>'submit', -value=>'Login'),
					'</form>'),
				div({-class=>'ftd ralign'},
					a({-href=>'register.cgi', -class=>'strong'}, 'Register')));
	}
	
	return div({-id=>'cpanel'}, $retval);
}


sub yaali
{
	my $user = shift;
	my @retval =
	(
		'You are already logged in as ',
		a({-href=>'member.cgi?id='.$user->{ID}},
			escapeHTML($user->{USERNM})).'. ',
		a({-href=>'logout.cgi'}, 'Logout').'?'
	);
	return wantarray ? @retval : "@retval";
}
sub yanli
{
	my @retval =
	(
		'You are not logged in. ',
		'('.a({-href=>'login.cgi'}, 'Login'),
		' or ',
		a({-href=>'register.cgi'}, 'Register').')'
	);
	return wantarray ? @retval : "@retval";
}
sub nl2br
{
	my $str = shift;
	$str =~ s/\n/<br \/>/g;
	return $str;
}

sub bad_deal
{
	print header($fourm::http_header),forum_start(),forum_error(@_),forum_end();
	exit;
}
sub good_deal
{
	print header($forum::http_header), forum_start(), @_, forum_end();
	exit;
}

sub sess_id_cookie
{
  return cookie(-name=>'forum_sess_id',-value=>shift,-path=>$forum::root_path);
}






my $mbcode_regex1 = qr/\[([^\[\]<>]+)\]([^\[\]]*)\[\/\]/;
my $mbcode_regex2 = qr/\{(link|list|img):([^{}]*)\}/i;

sub mbcode2
{
	my $match = shift;
	my $tag = lc shift;
	my @data = split '\|', shift();
	if ($tag eq 'list')
	{
		my $items = '';
		for my $d (@data)
		{
			$items .= "<li>$d</li>";
		}
		return "<ul>$items</ul>";
	}
	if ($tag eq 'link')
	{
		my ($url, $text) = @data;
		return $match if (!defined $url);
		
		$text = $url if (!defined $text or $text eq '');
		return qq(<a href="$url">$text</a>);
	}
	if ($tag eq 'img')
	{
		my ($src, $alt, $title) = @data;
		return $match if (!defined $src and $src eq '');
		
		$alt = '' unless defined $alt;
		$title = '' unless defined $title;
		return qq(<img src="$src" alt="$alt" title="$title" />);
	}
	return $match;
}
sub mbcode1
{
	shift;
	my ($style,$inner) = @_;
	$style =~ s/\n//g;
	return qq(<span style="$style">$inner</span>);
}
sub mbcode
{
	my $s = shift;
	while($s=~s/$mbcode_regex1/mbcode1(substr($s,$-[0],$+[0]-$-[0]),$1,$2)/e){}
	while($s=~s/$mbcode_regex2/mbcode2(substr($s,$-[0],$+[0]-$-[0]),$1,$2)/e){}
	return $s;
}

my $escape_regex = qr/\\([\[\]\{\}\|\\])/;
sub as_post
{
	my $str = escapeHTML(shift);
	$str =~ s/$escape_regex/'&#'.ord($1).';'/eg;
	return nl2br(mbcode($str));
}




my @months = qw(January February March April May June July
				August September October November December);
my @days = qw(Sunday Monday Tuesday Wednesday Thursday Friday Saturday);
my $time_regex = qr/^(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)$/;
sub timefmt
{
	my $mysql_time = shift;
	if ($mysql_time =~ $time_regex)
	{
		my ($yr,$mo,$dy,$hr,$mi) = ($1, $2-1, $3+0, $4, $5);
		my $ap = ($hr < 12) ? 'am' : 'pm';
		$hr = ($hr % 12) || 12;
		return "$months[$mo] $dy $yr, $hr:$mi$ap";
	}
	return $mysql_time;
	#my ($sec, $min, $hour, $dom, $month, $year, $dow) = strptime(shift);
}
sub priv
{
	my $priv = shift;
	return 'Administrator' if $priv eq 'A';
	return 'Moderator' if $priv eq 'M';
	return 'Member' if $priv eq 'U';
	return 'Unknown';
}


1;
